package com.ysx.server.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ysx.server.mapper.CategoryMapper;
import com.ysx.server.mapper.GoodsMapper;
import com.ysx.server.pojo.dto.CategoryPageQueryDTO;
import com.ysx.server.pojo.dto.GoodsDTO;
import com.ysx.server.pojo.entity.Category;
import com.ysx.server.pojo.entity.Goods;
import com.ysx.server.pojo.vo.CategoryVO;
import com.ysx.server.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 新增商品类型
     *
     * @param category
     * @return
     */
    @Override
    public boolean save(Category category) {
        if(category==null){
            return false;
        }
        categoryMapper.save(category);
        return true;
    }

    @Override
    public Page<Category> page(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getCurrent(),categoryPageQueryDTO.getPageSize());
        return categoryMapper.page(categoryPageQueryDTO);
    }

    /**
     * 商品类型更新
     *
     * @param category
     * @return
     */
    @Override
    @Transactional
    public boolean updateCategory(Category category) {
        //1.查询该分类的商品 根据分类id查询
        List<Goods> goodsList=goodsMapper.getByCategoryId(category.getId());
        //2.修改该分类的商品的分类信息
        goodsList.forEach(goods -> {
            if(!goods.getTypeName().equals(category.getCategoryName())){
                goods.setTypeName(category.getCategoryName());
                GoodsDTO goodsDTO = new GoodsDTO();
                BeanUtils.copyProperties(goods,goodsDTO);
                goodsMapper.update(goodsDTO);
            }
        });
        //3.修改分类信息
        return categoryMapper.update(category);
    }

    /**
     * 删除商品分类
     *
     * @param id
     * @return
     */
    @Override
    public boolean delCategory(Long id) {
        if(id==null||id<0){
            return false;
        }
        return categoryMapper.deleteById(id);
    }

    /**
     * 获取商品类型
     *
     * @return
     */
    @Override
    public List<CategoryVO> getCategory() {
        List<Category> categories=categoryMapper.getCategory();
        List<CategoryVO> categoryVO=new ArrayList<>();
        categories.forEach(category -> {
            categoryVO.add(new CategoryVO(category.getId(),category.getCategoryName()));
        });
        return categoryVO;
    }
}
